import request from 'axios'
const apiKey = 'ef31d002acda4eb29f4d7c035a2a2fe7'
const apiHost = 'mg3h2nckje.re.qweatherapi.com'

export function getCityId(cityName) {
  const url = 'https://' + apiHost + '/geo/v2/city/lookup'
  return request(url, {
    method: 'get',
    params: {
      location: cityName,
      key: apiKey,
    },
  })
}
//即时天气预报
export async function weatherNow(cityName) {
  const city = await getCityId(cityName)
  const cityId = city.data.location[0].id
  const url = 'https://' + apiHost + '/v7/weather/now'
  return request(url, {
    method: 'get',
    params: {
      location: cityId,
      key: apiKey,
    },
  })
}
//天气日报
export async function weatherDay(cityName, days) {
  const daysArr = [3, 7, 10, 15, 30]
  const index = daysArr.findIndex((item) => days == item)
  if (index < 0) {
    alert('日期输入错误，请重新输入')
    return
  }
  const city = await getCityId(cityName)
  const cityId = city.data.location[0].id
  //如果需要在字符串中引入变量的值，`需要使用${变量名`
  const url = 'https://' + apiHost + `/v7/weather/${days}d`
  return request(url, {
    method: 'get',
    params: {
      location: cityId,
      key: apiKey,
    },
  })
}
//24小时天气预报
export async function weather24Hour(cityName) {
  const city = await getCityId(cityName)
  const cityId = city.data.location[0].id
  //如果需要在字符串中引入变量的值，`需要使用${变量名`
  const url = 'https://' + apiHost + `/v7/weather/24h`
  return request(url, {
    method: 'get',
    params: {
      location: cityId,
      key: apiKey,
    },
  })
}
